import json
import random
import re


from django.contrib.auth.hashers import make_password
from django.db.models import Q
from django.shortcuts import render

from rest_framework.response import Response
from rest_framework.views import APIView

from user import userser, models
from user.models import UserModel
from utils.authorization import MyAuthentication

from utils.jwttool import tooljwt
from utils.myredis import redistoll
from utils.sendmsg import send_message
from .tasks import add, send


# Create your views here.


class Loginpwd(APIView):
    def post(self,request):
        account = request.data.get('account')
        password = request.data.get('password')
        info = UserModel.objects.filter(Q(username=account) | Q(email=account) |Q(phone=account)).first()
        if info is None:
            return Response({"code":400,"msg":"账号不存在"})
        elif info.password == password:
            data={
                "id":info.id,
                "account":account,
                "token":tooljwt.getToken(info.id,account)
            }
            if info.headimg:
                data["headimg"]=info.headimg
            else:
                data["headimg"]="/uploads/6.jpg"
            return Response({"msg":'登陆成功', "data": data, "code": 200})
        else:
            return Response({"code":400,"msg":"密码错误"})

class SendCode(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        code = str(random.randint(1000,9999))
        # result = send_message(phone,code)
        rediscode = redistoll.getstr(phone)
        if rediscode:
            return Response({"code": 400, "msg": '请勿重复发送'})
        else:
            send.delay(phone,code)
            redistoll.setstr(phone,code,60*2)
            return Response({"code":200,"msg":'发送成功'})
        # res = json.loads(result)
        # if res["statusCode"]=="000000":
        #     redistoll.setstr(phone,code,60*5)
        #     return Response({"code":200,"msg":'发送成功'})
        # else:
        #     return   Response({"code":400,"msg":'发送失败'})

class Login(APIView):
    def post(self,request):
        account = request.data.get('account')
        code = request.data.get('code')
        rediscode = redistoll.getstr(account)
        print(code, rediscode)
        if code != rediscode:
            return Response({"code":400,"msg":"验证码错误"})
        info = UserModel.objects.filter(phone=account,isshow=1).first()
        if info is None:
            newdata = UserModel.objects.create(phone=account)
            token = tooljwt.getToken(newdata.id,newdata.phone)
            id = newdata.id
            return Response({"code": 200, "msg": "登陆成功", "data": {"token": token, "id": id, "account": account}})
        token = tooljwt.getToken(info.id,info.phone)
        id = info.id
        return Response({"code":200,"msg":"登陆成功","data":{"token":token,"id":id,"account":account}})

class Check(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        info = UserModel.objects.filter(phone=phone).first()
        if info:
            return Response({"msg":"该手机已被注册","code":400})
        else:
            return Response({"msg":"该手机号可以使用","code":200})
class Register(APIView):
    def post(self, request):
        data = {}
        account = request.data.get('account')
        password = request.data.get('password')
        code = request.data.get('code')
        rediscode = redistoll.getstr(account)
        # if account == "" or password == "":
        #     return Response({"msg":"账号或密码不能为空","code":400})

        email_pattern = re.compile(r'^[a-zA-Z0-9]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
        if re.match(email_pattern,account):
            data["email"]=account
        elif re.match(r'^1[3-9]\d{9}$',account):
            if models.UserModel.objects.filter(phone=account).exists():
                return Response({"code":400,"msg":"手机号已经存在"})
            if code is None:
                return Response({"code":400,"msg":"验证码不能为空"})
            elif code != rediscode:
                return Response({"code":401,"msg":"验证码错误"})
            else:
                data["phone"]=account
        else:
            data["username"]=account
        data["password"]=password
        ser = userser.UserSerializer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"注册成功","code":200})
        else:
            return Response(ser.errors)


class TestUser(APIView):
    def post(self,request):
        sum_ = add.delay(1, 2)#异步任务的调用  通过delay
        print(sum_.get())
        return Response({"code": 200, "msg": "测试成功"})


class Cart(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        return Response({"code": 200, "msg": "购物车"})


